package com.push.xu.xpush.base;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Application;
import android.content.Context;

import java.util.List;

import android.os.AsyncTask;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.os.Process;
import android.util.Log;
import android.app.ActivityManager;

import com.huawei.android.hms.agent.HMSAgent;
import com.push.xu.xpush.constant.SystemTarget;
import com.push.xu.xpush.core.ZPushContext;
import com.push.xu.xpush.listener.ZPushRegisterListener;
import com.push.xu.xpush.util.RomUtil;
import com.push.xu.xpush.util.Utils;


public class PushBaseApplication extends Application {
	private Application mApplication;
	private HandlerThread mPushThread;
	private Handler mPushHandler;
	
	/**
	 * 根据手机型号初始化推送注册
	 * （华为推送如果收不到推送，需要注意SHA256是否上传正确，检查appid，华为移动服务是否为最新；
	 * 还是不行，清理一下手机中华为移动服务数据，查看下返回token是否异常；
	 * 或者签名打包测试，对比一下SHA256，比较靠谱；
	 */
	@Override
	public void onCreate() {
		mApplication = this;
		super.onCreate();

		Utils.init(this);

		String MY_PKG_NAME = this.getPackageName();
		String currentProcessName = getCurrentProcessName();
		Log.d("currentpro", "currentProcessName:"+currentProcessName+"|"+MY_PKG_NAME);

		mPushThread = new HandlerThread("push_init_handlerThread");
		mPushThread.start();
		mPushHandler = new Handler(mPushThread.getLooper()){
			@Override
			public void handleMessage(Message msg) {
				ZPushContext.getInstance().init(PushBaseApplication.this, new ZPushRegisterListener() {

					@Override
					public boolean onRegisterPush(String platformName) {
						boolean result = false;
						if (RomUtil.isMIUI()) {
							result=  platformName.equals(String.valueOf(SystemTarget.MIUI));
						} else if (RomUtil.isEMUI()) {
							HMSAgent.init(mApplication);
							result= platformName.equals(String.valueOf(SystemTarget.EMUI));
						} else {
							result= platformName.equals(String.valueOf(SystemTarget.JPUSH));
						}
						return result;
					}
				});
				ZPushContext.getInstance().register();
			}
		};

		if (MY_PKG_NAME.equals(currentProcessName)) {
			mPushHandler.sendEmptyMessage(0);
		}
	}
	
	 /**
     * 获取当前进程名称
     *
     * @return processName
     */
	 @SuppressLint("NewApi")
	public String getCurrentProcessName() {
        int currentProcessId = Process.myPid();
        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo runningAppProcess : runningAppProcesses) {
            if (runningAppProcess.pid == currentProcessId) {
                return runningAppProcess.processName;
            }
        }
        return null;
    }

}
